package com.attilax.web;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.imageio.IIOException;
import javax.imageio.ImageIO;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.reflect.MethodUtils;

//PBG import aaaCfg.IocX4nodb;

import com.attilax.core;
import com.attilax.hre.UrlDslParserV2;
import com.attilax.json.AtiJson;
import com.attilax.ref.refx;
import com.sun.image.codec.jpeg.JPEGCodec;

/**
 * com.attilax.web.PicReadServlet /CommonServlet?$method=
 * com.attilax.up.FileUploadService.upload
 * 
 * /CommonServlet?$method= com.attilax.up.FileUploadService.process
 * 
 * @author Administrator
 *
 */

// @//WebServlet(name = "PicReadServlet_name", urlPatterns = "/PicReadServlet")
public class PicReadServlet implements Servlet {

	public static void main(String[] args) {
		System.out.println("--f");
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public ServletConfig getServletConfig() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getServletInfo() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void init(ServletConfig paramServletConfig) throws ServletException {
		// TODO Auto-generated method stub

	}

	public static ThreadLocal<ServletResponse> resp = new ThreadLocal<ServletResponse>();

	@Override
	public void service(ServletRequest req, ServletResponse paramServletResponse)
			throws IOException, ServletException {
		req.setCharacterEncoding("utf8");
		resp.set(paramServletResponse);
		String src = req.getParameter("src");
		File file=new File(src);

		if (!new File(src).exists()) {
			String src_gbk2utf8 = new String(src.getBytes("gbk"), "utf8");

			if (!new File(src_gbk2utf8).exists())
				throw new RuntimeException("file not exist,oriDecode:" + src
						+ ",src_gbk2utf8:" + src_gbk2utf8);
			else
				file=new File(src_gbk2utf8);
		}

		BufferedImage bi;
		try {
			bi = ImageIO.read(file);

		} catch (Exception e) {
			bi = jpgRead(file);
		}
		try {

			ImageIO.write(bi, "jpg", paramServletResponse.getOutputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			paramServletResponse.getWriter().println(AtiJson.toJson(e));
			// throw new RuntimeException(e);
		}

		// paramServletResponse.getWriter().println(ret);

	}

	private BufferedImage jpgRead(File file) {
		try {
			BufferedImage bi;
			com.sun.image.codec.jpeg.JPEGImageDecoder decoder = JPEGCodec
					.createJPEGDecoder(new FileInputStream(file));
			bi = decoder.decodeAsBufferedImage();
			return bi;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;

	}

}
